/**
 * Created by bolin on 2016/12/13.
 */
var command = {
    addactivity: 0,
    addrules: 1,
    nulloperation: 3,
    moveactivity: 4,
    moverule: 5,
    selectactivity: 2,
    selectrule: 8,
    zoomin: 6,
    zoomout: 7,
    movecanvas: 9,
    save: 10,
    copy: 11,
    paste: 12,
    delete: 13,
    undo: 14,
    redo: 15,
    create: 16,
    autoadjust: 17,
    showactivitypropertyconfig: 18,
    showrulepropertyconfig: 19,
    deleteactivity: 20,
    deleterule: 21,
    open: 22,
    syncx: 23,
    syncy: 24,
    export: 25,
    import: 26,
    lock: 27
}
var StyleDefine = {
    Activity: {
        'referenceLineStyle': 'rgba(255,0,0,0.8)',
        'capturelength': 10,
        Start: {
            'Radius': 15
        },
        End: {
            'Radius': 15
        },
        Drafting: {
            'activityRectVertexX': 57.5,
            'activityRectVertexY': 22,
            'activityRectAngle': 8,
            'activityRectWidth': 115,
            'activityRectHeight': 44,
            'imgWidth': 0,
            'imgHeight': 0,
            'font': 12
        },
        Approval: {
            'activityRectVertexX': 57.5,
            'activityRectVertexY': 22,
            'activityRectAngle': 11,
            'activityRectWidth': 115,
            'activityRectHeight': 44,
            'imgWidth': 10,
            'imgHeight': 10,
            'font': 12
        },
        Merging: {
            'diamondWidth': 18,
            'diamondHeight': 18
        },
        Branching: {
            'diamondWidth': 18,
            'diamondHeight': 18
        },
        Condition: {
            'diamondWidth': 57.5,
            'diamondHeight': 22
        }
    },
    Arrow: {
        'arrowLength': 15,
        'arrowAngle': 8
    },
    Rule: {
        'SelectRadius': 7,
        'referenceLineStyle': 'rgba(255,0,0,0.8)',
        'capturelength': 10,
        'strokeStyle': "#0000ff"

    },
    Window: {
        'width': 2000,
        'height': 1600
    }
}
var ActivityType = {
    /// <summary>
    /// 开始节点
    /// </summary>
    'start': 0,
    /// <summary>
    /// 结束
    /// </summary>
    'end': 1,
    /// <summary>
    /// 起草节点
    /// </summary>
    'drafting': 2,

    /// <summary>
    /// 条件分支
    /// </summary>
    'condition': 3,

    /// <summary>
    /// 审批节点（包含并行和串行两种模式）
    /// </summary>
    'approval': 4,
    /// <summary>
    /// 审阅节点
    /// </summary>
    'freedom': 4,

    /// <summary>
    /// 分支
    /// </summary>
    'work': 5,
    /// <summary>
    /// 合并
    /// </summary>
    'freedom': 6,
    /// <summary>
    /// 子流程
    /// </summary>
    'subprocesses': 7

}
TemplateStatus = {
    None: -1,
    New: 0,
    Open: 1,
    Import: 2

}
var ActivityPropertyStatus = {
    /// <summary>
    /// 是否编辑表单
    /// </summary>
    ENABLE_EDIT_ATTACHMENT: "0|2",
    //是否添加附件
    ENABLE_ATTACHMENT: "2|2",
    /// <summary>
    /// 是否查看审批历史
    /// </summary>
    ENABLE_SHOW: "4|2",
    /// <summary>
    /// 是否提交意见
    /// </summary>
    ENABLE_SUGGESTION: "6|2",
    /// <summary>
    /// 是否需要签名
    /// </summary>
    ENABLE_SIGNATURE: "8|2",
    /// <summary>
    /// 是否终止流程
    /// </summary>
    ENABLE_TERMINATE_FLOW: "10|2",
    /// <summary>
    /// 合并审批节点
    /// </summary>
    IS_MERGR: "12|2",
    /// <summary>
    /// 是否转批
    /// </summary>
    ENABLE_TRANSFER: "14|2",
    /// <summary>
    /// 是否传阅
    /// </summary>
    ENABLE_CIRCULATED: "16|2",
    /// <summary>
    /// 是否归档
    /// </summary>
    ENABLE_FILED: "18|2",
    /// <summary>
    /// 是否人工决策
    /// </summary>
    IS_ARTIFICIAL_DECISION: "20|2",
    /// <summary>
    /// 选人方式
    /// </summary>
    IS_AUTOMATIC: "22|2",
    /// <summary>
    /// 完成方式
    /// </summary>
    FINISH_TYPE: "24|2",
    /// <summary>
    /// 在线公文打开方式
    /// </summary>
    OPEN_MODE_TYPE: "26|4",
    /// <summary>
    /// 是否限制上传附件
    /// </summary>
    IS_UPLOAD_AUTOMATIC: "30|2"
}
var BaseProperty = {
    ActivityProperty: {
        activityName: {
            'id': 'activityName',
            'name': 'activityName',
            'title': "节点名称",
        },
        description: {
            'id': 'description',
            'name': 'description',
            'title': "描述",
        },
        FINISH_TYPE: {
            'id': 'FINISH_TYPE',
            'name': 'FINISH_TYPE',
            'title': "完成方式",
            'array': [['0', '单一'], ['1', '百分比'], ['2', '数量'], ['3', '全部']]
        },
        finishNumber: {
            'id': 'finishNumber',
            'name': 'finishNumber',
            'title': "完成数量"
        },
        IS_AUTOMATIC: {
            'id': 'IS_AUTOMATIC',
            'name': 'IS_AUTOMATIC',
            'title': "选人方式",
            'array': [['0', '手工选人'], ['1', '自动选人']]
        },
        IS_UPLOAD_AUTOMATIC: {
            'id': 'IS_UPLOAD_AUTOMATIC',
            'name': 'IS_UPLOAD_AUTOMATIC',
            'title': "限制上传附件"
        },
        ENABLE_ATTACHMENT: {
            'id': 'ENABLE_ATTACHMENT',
            'name': 'ENABLE_ATTACHMENT',
            'title': "上传附件"
        },
        OPEN_MODE_TYPE: {
            'id': 'OPEN_MODE_TYPE',
            'name': 'OPEN_MODE_TYPE',
            'title': "打开模式",
            'array': [['0', '强制保留痕迹'], ['1', '核稿模式'], ['2', '普通编辑模式'], ['3', '只读模式'], ['4', '手写模式']]
        },
        //是否编辑表单
        ENABLE_EDIT_ATTACHMENT: {
            'id': 'ENABLE_EDIT_ATTACHMENT',
            'name': 'ENABLE_EDIT_ATTACHMENT',
            'title': "编辑表单"
        },
        ENABLE_ATTACHMENT: {
            'id': 'ENABLE_ATTACHMENT',
            'name': 'ENABLE_ATTACHMENT',
            'title': "上传附件"
        },
        //是否查看审批历史
        ENABLE_SHOW: {
            'id': 'ENABLE_SHOW',
            'name': 'ENABLE_SHOW',
            'title': "审批历史"
        },
        //是否提交意见
        ENABLE_SUGGESTION: {
            'id': 'ENABLE_SUGGESTION',
            'name': 'ENABLE_SUGGESTION',
            'title': "意见"
        },
        //是否终止流程
        ENABLE_TERMINATE_FLOW: {
            'id': 'ENABLE_TERMINATE_FLOW',
            'name': 'ENABLE_TERMINATE_FLOW',
            'title': "终止"
        },
        //是否需要签名
        ENABLE_SIGNATURE: {
            'id': 'ENABLE_SIGNATURE',
            'name': 'ENABLE_SIGNATURE',
            'title': "签名"
        },
        ENABLE_TRANSFER: {
            'id': 'ENABLE_TRANSFER',
            'name': 'ENABLE_TRANSFER',
            'title': "转批"
        },
        ENABLE_CIRCULATED: {
            'id': 'ENABLE_CIRCULATED',
            'name': 'ENABLE_CIRCULATED',
            'title': "传阅"
        },
        ENABLE_FILED: {
            'id': 'ENABLE_FILED',
            'name': 'ENABLE_FILED',
            'title': "归档"
        },
        IS_MERGR: {
            'id': 'IS_MERGR',
            'name': 'IS_MERGR',
            'title': "合并审批"
        }
    },
    InitialPage: function (parent, activity) {
        this.activity = activity;
        this.InitialControl(parent);
        this.InitialData(activity);
    },
    InitialData: function () {
        debugger;
        var me = this;
        this.ActivityProperty.activityName.control.val(this.activity.ActivityName);
        if (this.activity.ActivityProperty != undefined) {
            this.ActivityProperty.activityName.control.val(this.activity.ActivityProperty.activityName);
            this.ActivityProperty.description.control.val(this.activity.ActivityProperty.description);
            this.ActivityProperty.FINISH_TYPE.control.val(this.activity.ActivityProperty.FINISH_TYPE);
            this.ActivityProperty.finishNumber.control.val(this.activity.ActivityProperty.finishNumber);

            if (this.activity.ActivityProperty.FINISH_TYPE == 1 || this.activity.ActivityProperty.FINISH_TYPE == 2) {
                this.ActivityProperty.finishNumber.control.removeAttr("disabled");
            }
            else {
                this.ActivityProperty.finishNumber.control.attr("disabled", "disabled");
                this.ActivityProperty.finishNumber.control.val('');
            }
            this.ActivityProperty.IS_AUTOMATIC.control.val(this.activity.ActivityProperty.IS_AUTOMATIC);
            this.ActivityProperty.OPEN_MODE_TYPE.control.val(this.activity.ActivityProperty.OPEN_MODE_TYPE);
            if (this.activity.ActivityProperty.ENABLE_EDIT_ATTACHMENT == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control);

            if (this.activity.ActivityProperty.ENABLE_ATTACHMENT == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_ATTACHMENT.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_ATTACHMENT.control);
            if (this.activity.ActivityProperty.IS_UPLOAD_AUTOMATIC == 1)
                this.SetCheck(this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control);
            else
                this.SetUnCheck(this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control);

            if (this.activity.ActivityProperty.ENABLE_SHOW == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SHOW.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SHOW.control)
            if (this.activity.ActivityProperty.ENABLE_SUGGESTION == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SUGGESTION.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SUGGESTION.control);
            //if (this.activity.ActivityProperty.ENABLE_TRANSIT == 1)
            //    this.SetCheck(this.ActivityProperty.ENABLE_TRANSIT.control);
            //else
            //    this.SetUnCheck(this.ActivityProperty.ENABLE_TRANSIT.control);
            if (this.activity.ActivityProperty.ENABLE_TERMINATE_FLOW == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_TERMINATE_FLOW.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_TERMINATE_FLOW.control);
            if (this.activity.ActivityProperty.ENABLE_SIGNATURE == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_SIGNATURE.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_SIGNATURE.control);
            if (this.activity.ActivityProperty.ENABLE_TRANSFER == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_TRANSFER.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_TRANSFER.control);
            if (this.activity.ActivityProperty.ENABLE_CIRCULATED == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_CIRCULATED.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_CIRCULATED.control);
            if (this.activity.ActivityProperty.ENABLE_FILED == 1)
                this.SetCheck(this.ActivityProperty.ENABLE_FILED.control);
            else
                this.SetUnCheck(this.ActivityProperty.ENABLE_FILED.control);
            if (this.activity.ActivityProperty.IS_MERGR == 1)
                this.SetCheck(this.ActivityProperty.IS_MERGR.control);
            else
                this.SetUnCheck(this.ActivityProperty.IS_MERGR.control);
        }
        else {
            this.ActivityProperty.description.control.val('');
            this.ActivityProperty.FINISH_TYPE.control.val(0);
            this.ActivityProperty.finishNumber.control.attr("disabled", "disabled");
            this.ActivityProperty.finishNumber.control.val('');
            this.ActivityProperty.IS_AUTOMATIC.control.val(0);
            this.ActivityProperty.OPEN_MODE_TYPE.control.val(0);
            this.ActivityProperty.ENABLE_EDIT_ATTACHMENT.control.attr("checked", false);
            this.ActivityProperty.ENABLE_ATTACHMENT.control.attr("checked", false);
            this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control.attr("checked", false);

            this.ActivityProperty.ENABLE_SHOW.control.attr("checked", false);
            this.ActivityProperty.ENABLE_SUGGESTION.control.attr("checked", false);
            //this.ActivityProperty.ENABLE_TRANSFER.control.attr("checked", false);
            this.ActivityProperty.ENABLE_TERMINATE_FLOW.control.attr("checked", false);
            this.ActivityProperty.ENABLE_SIGNATURE.control.attr("checked", false);
            this.ActivityProperty.ENABLE_TRANSFER.control.attr("checked", false);
            this.ActivityProperty.ENABLE_CIRCULATED.control.attr("checked", false);
            this.ActivityProperty.ENABLE_FILED.control.attr("checked", false);
            this.ActivityProperty.IS_MERGR.control.attr("checked", false);

        }
    },
    InitialControl: function (parent) {
        parent.empty();
        var activityType = this.activity.activityType;
        var form = $('<form class="form-horizontal" role="form">');
        parent.append(form);
        switch (activityType) {
            case ActivityType.start:
                start(form, this);
                break;
            case ActivityType.end:
                end(form, this);
                break;
            case ActivityType.drafting:
                drafting(form, this);
                break;
            case ActivityType.approval:
                approval(form, this);
                break;
            case ActivityType.condition:
                condition(form, this);
                break;
            case ActivityType.freedom:
                freedom(form, this);
                break;
        }
        function start(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            )
        }

        function end(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_FILED, 2, 2)
                )
            )
        }

        function drafting(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_UPLOAD_AUTOMATIC, 2)
                )
            )
        }

        function approval(form, that) {
            form.append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.activityName, 2)
                ).append(
                    input(that.ActivityProperty.activityName, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.description, 2)
                ).append(
                    input(that.ActivityProperty.description, 10)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.FINISH_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.FINISH_TYPE, 2)
                ).append(
                    input(that.ActivityProperty.finishNumber, 2)
                ).append(
                    label(that.ActivityProperty.IS_AUTOMATIC, 2)
                ).append(
                    select(that.ActivityProperty.IS_AUTOMATIC, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_UPLOAD_AUTOMATIC, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    label(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                ).append(
                    select(that.ActivityProperty.OPEN_MODE_TYPE, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_EDIT_ATTACHMENT, 2, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_ATTACHMENT, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_SHOW, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_SUGGESTION, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_TERMINATE_FLOW, 2)
                )
            ).append(
                $('<div class="form-group">').append(
                    checkbox(that.ActivityProperty.ENABLE_SIGNATURE, 2, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_TRANSFER, 2)
                ).append(
                    checkbox(that.ActivityProperty.ENABLE_CIRCULATED, 2)
                ).append(
                    checkbox(that.ActivityProperty.IS_MERGR, 2)
                )
            )
        }

        function condition(form, that) {

        }

        function freedom(form, that) {

        }

        function label(data, column, offset) {
            var result = $($.format('<label class="col-sm-{0} col-sm-offset-{1} control-label no-padding-right">', column, offset == undefined ? 0 : offset)).html(data.title)
                .attr('class', 'col-sm-2 control-label no-padding-right').attr('for', data.name)
            return result;
        }

        function input(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                data.control = $('<input class="form-control" type="text">').attr('id', data.id).attr('name', data.name).attr('placeholder', data.title)
            )
            return result;
        }

        function checkbox(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                $('<div class="checkbox">').append(
                    $('<label>').append(
                        data.control = $('<input class="colored-success" type="checkbox">').attr('id', data.id).attr('name', data.name)
                    ).append(
                        $('<span class="text">').html(data.title)
                    )
                )
            )
            return result;
        }

        function select(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                option(data)
            )
            return result;
            function option(data) {
                data.control = $('<select >').attr('id', data.id).attr('name', data.name)
                $.each(data.array, function (i, val) {
                    data.control.append($('<option>').attr('value', val[0]).html(val[1]));
                })
                return data.control;
            }
        }
    },
    SaveData: function (activity) {
        if (activity.ActivityProperty == undefined) {
            activity.ActivityProperty = {};
        }
        activity.ActivityProperty.activityName = this.ActivityProperty.activityName.control == undefined ? '' : this.ActivityProperty.activityName.control.val();
        activity.ActivityProperty.description = this.ActivityProperty.description.control == undefined ? '' : this.ActivityProperty.description.control.val();
        activity.ActivityProperty.FINISH_TYPE = this.ActivityProperty.FINISH_TYPE.control == undefined ? '' : this.ActivityProperty.FINISH_TYPE.control.find("option:selected").val();
        activity.ActivityProperty.finishNumber = this.ActivityProperty.finishNumber.control == undefined ? '' : this.ActivityProperty.finishNumber.control.val();
        activity.ActivityProperty.IS_AUTOMATIC = this.ActivityProperty.IS_AUTOMATIC.control == undefined ? '' : this.ActivityProperty.IS_AUTOMATIC.control.find("option:selected").val();
        activity.ActivityProperty.OPEN_MODE_TYPE = this.ActivityProperty.OPEN_MODE_TYPE.control == undefined ? '' : this.ActivityProperty.OPEN_MODE_TYPE.control.find("option:selected").val();
        activity.ActivityProperty.ENABLE_ATTACHMENT = this.ActivityProperty.ENABLE_ATTACHMENT.control == undefined ? '' : this.ActivityProperty.ENABLE_ATTACHMENT.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.IS_UPLOAD_AUTOMATIC = this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control == undefined ? '' : this.ActivityProperty.IS_UPLOAD_AUTOMATIC.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SHOW = this.ActivityProperty.ENABLE_SHOW.control == undefined ? '' : this.ActivityProperty.ENABLE_SHOW.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SUGGESTION = this.ActivityProperty.ENABLE_SUGGESTION.control == undefined ? '' : this.ActivityProperty.ENABLE_SUGGESTION.control.is(":checked") ? 1 : 0;
        //activity.ActivityProperty.ENABLE_TRANSIT = this.ActivityProperty.ENABLE_TRANSFER.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_TERMINATE_FLOW = this.ActivityProperty.ENABLE_TERMINATE_FLOW.control == undefined ? '' : this.ActivityProperty.ENABLE_TERMINATE_FLOW.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_SIGNATURE = this.ActivityProperty.ENABLE_SIGNATURE.control == undefined ? '' : this.ActivityProperty.ENABLE_SIGNATURE.control.is(":checked") ? 1 : 0;
        activity.ActivityName = this.ActivityProperty.activityName.control == undefined ? '' : this.activity.ActivityProperty.activityName;
        activity.ActivityProperty.ENABLE_TRANSFER = this.ActivityProperty.ENABLE_TRANSFER.control == undefined ? '' : this.ActivityProperty.ENABLE_TRANSFER.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_CIRCULATED = this.ActivityProperty.ENABLE_CIRCULATED.control == undefined ? '' : this.ActivityProperty.ENABLE_CIRCULATED.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.ENABLE_FILED = this.ActivityProperty.ENABLE_FILED.control == undefined ? '' : this.ActivityProperty.ENABLE_FILED.control.is(":checked") ? 1 : 0;
        activity.ActivityProperty.status = 0;
        for (i in ActivityPropertyStatus) {
            var option = ActivityPropertyStatus[i];
            var op = option.split('|');
            op[0] = parseInt(op[0]);
            op[1] = parseInt(op[1]);
            var tmp = (activity.ActivityProperty[i] << op[0]);
            activity.ActivityProperty.status |= tmp;
        }
    },

    //设置选择框被选中
    SetCheck: function (check) {
        if (check != undefined) {
            if (!check.is(":checked")) {
                check.click();
            }
        }
    },
    //取消选择框选中
    SetUnCheck: function (check) {
        if (check != undefined) {
            check.attr("checked", false);
        }
    }

}
var ReturnProperty = {

    ActivityProperty: {
        CanReturnRule: {
            'title': "可退回节点",
            'control': $('<select id="selectCanReturnRule" multiple="multiple" style="width: 100%;height: 267px">')
        },
        ReturnRule: {
            'title': "退回节点",
            'control': $('<select id="selectReturnRule" multiple="multiple" style="width: 100%;height: 267px">')
        }

    },

    InitialPage: function (parent, activity) {
        this.activity = activity;
        this.InitialControl(parent);
        this.InitialData(activity);
    },
    InitialControl: function (parent) {
        parent.empty();
        var that = this;
        var form = $('<form class="form-horizontal" role="form">');
        var btnRight, btnLeft;
        form.append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-4 col-sm-offset-2"   >').append(
                    $('<span>').html(that.ActivityProperty.CanReturnRule.title)
                )
            ).append(
                $('<div class="col-sm-4 col-sm-offset-2" >').append(
                    $('<span>').html(that.ActivityProperty.ReturnRule.title)
                )
            )
        ).append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-5" >').append(
                    that.ActivityProperty.CanReturnRule.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnRight = $('<input class="btn btn-blue" type="button"  style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnLeft = $('<input class="btn btn-blue" type="button"   style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    that.ActivityProperty.ReturnRule.control
                )
            )
        )

        btnRight.click(function () {
            var query = $('#selectCanReturnRule option:selected')
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.ReturnRule.control.append($(val));
            })
        })
        btnLeft.click(function () {
            var query = $("#selectReturnRule  option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.CanReturnRule.control.append($(val));
            })
        })
        parent.append(form);

    },
    //初始化数据（给控件绑定数据）
    InitialData: function (activity) {
        var me = this;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        // me.activity.GetReturnActivitys(true, me.activity.ID);
        if (activity.ActivityProperty != undefined && activity.ActivityProperty.WF_RULE != undefined) {
            //待选择项
            var tmp = new Array();
            for (i = 0; i < me.activity.Preactivity.length; i++) {
                if (me.activity.Preactivity[i].activityType != ActivityType.condition && me.activity.Preactivity[i].activityType != ActivityType.merging && me.activity.Preactivity[i].activityType != ActivityType.branching)
                    if (activity.ActivityProperty.WF_RULE.first(me.activity.Preactivity[i].guid, 'toGuid') == undefined)
                        tmp[tmp.length] = me.activity.Preactivity[i];
            }
            $.each(tmp, function (i, val) {
                if (val.guid != me.activity.guid) {
                    var option = $("<option value=" + val.guid + " title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanReturnRule.control.append(option);
                }
            });

            tmp = new Array();
            for (j = 0; j < activity.ActivityProperty.WF_RULE.length; j++) {
                var preac = me.activity.Preactivity.first(activity.ActivityProperty.WF_RULE[j].toGuid, 'guid');
                if (preac && !tmp.first(preac.guid))
                    tmp[tmp.length] = preac;
            }
            $.each(tmp, function (i, val) {
                var option = $("<option value=" + val.guid + " title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                me.ActivityProperty.ReturnRule.control.append(option);
            });
        } else {
            $.each(me.activity.Preactivity, function (i, val) {
                if (val.activityType != ActivityType.condition && val.activityType != ActivityType.merging && val.activityType != ActivityType.branching) {
                    var option = $("<option value=" + val.guid + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanReturnRule.control.append(option);
                }
            });
        }
    },

    //保存数据
    SaveData: function (activity) {
        if (activity.ActivityProperty == undefined)
            activity.ActivityProperty = {};
        activity.ActivityProperty.WF_RULE = new Array();
        var query = $("#selectReturnRule  option");
        var j = 0;
        $.each(query, function (i, val) {
            var rule = new Object();
            rule.guid = Guid.NewGuid();

            rule.templateId = '';
            rule.ruleName = '';
            rule.IS_DEFAULT = 0;
            rule.description = '';
            rule.condition = '';
            rule.coordinate = '';
            rule.fromGuid = activity.guid;
            rule.toGuid = $(val).val();
            rule.ruleType = 0;
            rule.ruleType = 1;
            rule.isDel = 0;
            rule.CREATOR = GetCookie('TokenGuid');

            activity.ActivityProperty.WF_RULE[j] = rule;
            ++j;

        });

        activity.ActivityProperty.ENABLE_RETURN = activity.ActivityProperty.WF_RULE > 0 ? 0 : 1;
    }
}
var UserProperty = {
    ActivityProperty: {
        ParticipantType: {
            'typevalue': ''
        },
        RadioJob: {
            'title': "角色",
            'control': $("<input name='patype' type='radio' value='0' checked='checked'>")
        },
        RadioActivity: {
            'title': "活动",
            'control': $("<input name='patype' type='radio' value='1'>")
        },
        DivJob: {

            'control': $("<div style='width:100%;float:left;'>")
        },
        DivActivity: {

            'control': $("<div  style='width:100%;float:left; display:none;'>")
        },
        CanSelectJob: {
            'title': "可选角色",
            'AddRefresh': true,
            'control': $('<select  multiple="multiple" style="width: 100%;height: 267px">')
        },
        SelectedJob: {
            'title': "已选角色",
            'control': $("<ul style='border:1px solid rgba(0,0,0,.25); height:267px; overflow:auto;list-style: none;line-height: 20px !important; padding:5px 10px; '>")
        },
        CanSelectActivity: {
            'title': "可选步骤",
            'AddRefresh': false,
            'control': $('<select id="selectCanSelectActivity" multiple="multiple"  style="width: 100%;height: 267px">')
        },
        SelectedActivity: {
            'title': "已选步骤",
            'control': $('<select id="selectSelectedActivity" multiple="multiple" style="width: 100%;height: 267px">')
        }
    },

    InitialPage: function (parent, activity) {
        var me = this;
        me.parent = parent;
        me.activity = activity;
        me.InitialControl(parent);
        me.InitialData(activity);
    },
    InitialControl: function (parent) {
        parent.empty();
        var that = this;
        var form = $('<form class="form-horizontal" role="form">'), btnJobRight, btnJobLeft, btnActivityRight, btnActivityLeft, jobArea, activityArea;
        form.append(
            $('<div class="form-group">').append(
                $('<div class="col-sm-4 col-sm-offset-2"   >').append(
                    $('<div class="checkbox">').append(
                        $('<label >').append(
                            $(' <input name="radio"  type="radio" checked="checked" data-index="0">')
                        ).append(
                            $('<span class="text">').html("岗位")
                        )
                    )
                )
            ).append(
                $('<div class="col-sm-4 col-sm-offset-2" >').append(
                    $('<div class="checkbox">').append(
                        $('<label >').append(
                            $(' <input name="radio"  type="radio" data-index="1">')
                        ).append(
                            $('<span class="text">').html("活动节点")
                        )
                    )
                )
            )
        ).append(
            jobArea = $('<div class="form-group">').append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.CanSelectJob.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnJobRight = $('<input class="btn btn-blue" type="button" style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnJobLeft = $('<input class="btn btn-blue" type="button" style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.SelectedJob.control
                )
            )
        ).append(
            activityArea = $('<div class="form-group" style="display: none">').append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.CanSelectActivity.control
                )
            ).append(
                $('<div class="col-sm-2" style="vertical-align: middle;height: 100%">').append(
                    btnActivityRight = $('<input class="btn btn-blue" type="button" style="width: 100%;margin-top: 80px" value=">>>>>>">')
                ).append(
                    btnActivityLeft = $('<input class="btn btn-blue" type="button" style="width: 100%; margin-top: 20px"  value="<<<<<<">')
                )
            ).append(
                $('<div class="col-sm-5" >').append(
                    this.ActivityProperty.SelectedActivity.control
                )
            )
        )
        var radios = $('input[type=radio]', form);
        radios.click(function () {
            $this = $(this);
            var currentDataType = $this.data("index");
            if (currentDataType == 0) {
                activityArea.css('display', 'none');
                jobArea.css('display', 'block');
            } else {
                jobArea.css('display', 'none');
                activityArea.css('display', 'block');
            }
        })
        btnJobRight.click(function () {
            var query = that.ActivityProperty.CanSelectJob.control.find("option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.AppendTableRow($(val).val(), $(val).text(), "", that.ActivityProperty.SelectedJob);
            })
        })
        btnJobLeft.click(function () {
            var query = that.ActivityProperty.SelectedJob.control.find("li");
            $.each(query, function (i, val) {
                if (that.getBackgroundColor($(val)) == '#26a0da') {
                    var participantid = $(val).find("input").eq(0).val();
                    var participantname = $(val).find("span").eq(0).text();
                    var option = $("<option value=" + participantid + " title=" + participantname + ">" + participantname + "</option>");
                    that.ActivityProperty.CanSelectJob.control.append(option);
                    $(val).remove();
                }
            })
        })
        btnActivityRight.click(function () {
            var query = $('#selectCanSelectActivity option:selected')
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.SelectedActivity.control.append($(val));
            })
        })
        btnActivityLeft.click(function () {
            var query = $("#selectSelectedActivity  option:selected");
            $.each(query, function (i, val) {
                $(val).remove();
                that.ActivityProperty.CanSelectActivity.control.append($(val));
            })
        })
        parent.append(form);
    },
    //初始化控件数据
    InitialData: function (activity) {

        var me = this;
        this.ActivityProperty.CanSelectActivity.control.empty();
        this.ActivityProperty.SelectedActivity.control.empty();
        this.ActivityProperty.SelectedJob.control.empty();
        this.ActivityProperty.CanSelectJob.control.empty();
        if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants && activity.ActivityProperty.activityParticipants.length > 0 &&
            activity.ActivityProperty.activityParticipants[0].type) {
            this.ActivityProperty.ParticipantType.typevalue = activity.ActivityProperty.activityParticipants[0].type;
            if (this.ActivityProperty.ParticipantType.typevalue == "2") {
                this.SetCheck(this.ActivityProperty.RadioActivity.control);

            }
            else {
                this.SetCheck(this.ActivityProperty.RadioJob.control);
            }
        }
        else {
            this.ActivityProperty.ParticipantType.typevalue = "0";
            this.SetCheck(this.ActivityProperty.RadioJob.control);
        }
        this.InitialJobData(activity);
        this.InitialActivityData(activity);
    },

    InitialJobData: function (activity) {
        var me = this;
        var selectedJob = $("#selectSelectedJob option");
        //SqlHelper.GetAllJob();
        $.each(SqlHelper.JobList, function (i, val) {
            if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants != undefined) {
                var j = 0;
                var bSelected = false;
                for (h = 0; h < activity.ActivityProperty.activityParticipants.length; h++) {
                    if (val.id == activity.ActivityProperty.activityParticipants[h].participantId) {
                        j = h;
                        bSelected = true;
                        break;
                    }
                }
                if (bSelected) {
                    me.AppendTableRow(val.id, val.jobName, activity.ActivityProperty.activityParticipants[j].type, me.ActivityProperty.SelectedJob);
                }
                else {
                    var option = $("<option value=" + val.id + " title=" + val.jobName + ">" + val.jobName + "</option>");
                    me.ActivityProperty.CanSelectJob.control.append(option);
                }
            }
            else {
                var option = $("<option value=" + val.id + " title=" + val.jobName + ">" + val.jobName + "</option>");
                me.ActivityProperty.CanSelectJob.control.append(option);
            }
        });
    },

    InitialActivityData: function (activity) {
        var me = this;
        $.each(wf.activityHelper.Activitys, function (i, val) {
            val.LoopCount = 0;
        })
        wf.activityHelper.GetReturnActivitys(wf.activityHelper.DraftingActivity);
        //me.activity.GetReturnActivitys(true, me.activity.id);
        $.each(me.activity.Preactivity, function (i, val) {
            if (activity.ActivityProperty != undefined && activity.ActivityProperty.activityParticipants != undefined) {
                var j = 0;
                var bSelected = false;
                for (h = 0; h < activity.ActivityProperty.activityParticipants.length; h++) {
                    if (val.id == activity.ActivityProperty.activityParticipants[h].participantId) {
                        j = h;
                        bSelected = true;
                        break;
                    }
                }
                if (bSelected) {
                    var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.SelectedActivity.control.append(option);
                }
                else {
                    var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                    me.ActivityProperty.CanSelectActivity.control.append(option);
                }
            }
            else {
                var option = $("<option value=" + val.id + "  title=" + val.ActivityName + ">" + val.ActivityName + "</option>");
                me.ActivityProperty.CanSelectActivity.control.append(option);
            }
        });
    },

    SaveData: function (activity) {
        var me = this;

        if (me.ActivityProperty.RadioActivity.control.is(":checked")) {
            me.SaveActivityData(activity);
            activity.ActivityProperty.type = me.ActivityProperty.RadioActivity.control.val();
        }
        else {
            me.SaveJobData(activity);
            activity.ActivityProperty.type = me.ActivityProperty.RadioJob.control.val();
        }
    },

    SaveJobData: function (activity) {
        var me = this;
        activity.ActivityProperty.activityParticipants = new Array();
        var query = me.ActivityProperty.SelectedJob.control.find("li");

        $.each(query, function (i, val) {
            var participantid = $(val).find("input").eq(0).val();
            var participanttype = $(val).find("input[type=radio]").filter(':checked').val();
            activity.ActivityProperty.activityParticipants[activity.ActivityProperty.activityParticipants.length] = me.InitialParticipant(participanttype, participantid);
        })
    },

    SaveActivityData: function (activity) {
        var me = this;
        activity.ActivityProperty.activityParticipants = new Array();
        var query = me.ActivityProperty.SelectedActivity.control.find("option");
        $.each(query, function (i, val) {
            activity.ActivityProperty.activityParticipants[activity.ActivityProperty.activityParticipants.length] = me.InitialParticipant(2, $(val).val());
        })
    },

    InitialParticipant: function (participantType, participantId) {
        var me = this;
        var participant = new Object();

        participant.guid = me.activity.guid;
        participant.type = participantType;
        participant.participantId = participantId;
        participant.isDel = 0;
        return participant;
    },

    AppendTableRow: function (tbvalue, tbname, tbtype, Prop) {
        var me = this, radioPublic, radioPravite;

        var li = $("<li style='height:20px; width:240px; line-height:20px;font-size:12px; display: inline-block '>");
        li.append(
            $('<input style="display:none;" name="participantid"/>').val(tbvalue)
        ).append(
            $('<span style="float:left;  background-color:transparent;">').html(tbname)
        ).append(
            $('<div class="checkbox" style="display: inline-block;padding-top: 0px !important; margin-left: 10px;" >').append(
                $('<label >').append(
                    radioPublic = $('<input name="radio"  type="radio" data-index="0" value="0">').attr('name', tbvalue)
                ).append(
                    $('<span class="text">').html("监管")
                )
            )
        ).append(
            $('<div class="checkbox" style="display: inline-block;padding-top: 0px !important;margin-left: 10px;">').append(
                $('<label >').append(
                    radioPravite = $(' <input name="radio"  type="radio" data-index="1" value="1">').attr('name', tbvalue)
                ).append(
                    $('<span class="text">').html("全局")
                )
            )
        )
        debugger;
        if (tbtype == 0) {
            radioPublic.attr("checked", true);
            radioPravite.removeAttr("checked");
        } else {
            radioPravite.attr("checked", true);
            radioPublic.removeAttr("checked");
        }

        Prop.control.append(li);

        li.bind({
            "click": function (e) {
                if (e.button == 0) {
                    if (!e.ctrlKey) {
                        Prop.control.find("li").css("background-color", "white");
                    }
                    if (me.getBackgroundColor(li) == '#26a0da')
                        li.css("background-color", "white");
                    else
                        li.css("background-color", "#26a0da");
                }
            }, "mouseenter": function () {
                if (me.getBackgroundColor(li) != '#26a0da')
                    li.css("background-color", "#e8e8e8");
            }, "mouseleave": function () {
                if (me.getBackgroundColor(li) != '#26a0da')
                    li.css("background-color", "white");
            }

        });
    },

    SetCheck: function (check) {
        check.click();
    },
    //获取div的背景色
    /*
     不同浏览器获得背景色的表线形式不同
     这里将他们都格式化为 #ffffff 的格式
     */
    getBackgroundColor: function (control) {
        var rgb = control.css('background-color');
        if (rgb.indexOf('#') != -1 || rgb == 'transparent' || rgb == 'white')
            return rgb;
        //rgb(232, 232, 232)
        rgb = rgb.split('(')[1];
        rgb = rgb.substring(0, rgb.length - 1);
        rgb = rgb.split(',');


        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }

        return rgb = "#" + hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
    }

}
var ruleProperty = {

    RuleProperty: {
        ruleName: {
            'id': 'ruleName',
            'name': 'ruleName',
            'title': "规则名称"
        },
        expression: {
            'id': 'expression',
            'name': 'expression',
            'title': "表达式"
        }
    },
    //初始化页面
    InitialPage: function (parent, rule) {
        this.rule = rule;
        this.InitialControl(parent);
        this.InitialData(rule);
    },
    //初始化数据
    InitialData: function (rule) {
        var me = this;
        if (rule.RuleProperty != undefined) {
            me.RuleProperty.ruleName.control.val(rule.RuleProperty.ruleName);
            me.RuleProperty.expression.control.val(rule.RuleProperty.expression);
        }
    },

    InitialControl: function (parent) {
        parent.empty();
        var form = $('<form class="form-horizontal" role="form">');
        parent.append(form);
        form.append(
            $('<div class="form-group">').append(
                label(this.RuleProperty.ruleName, 2)
            ).append(
                input(this.RuleProperty.ruleName, 10)
            )
        ).append(
            $('<div class="form-group">').append(
                label(this.RuleProperty.expression, 2)
            ).append(
                input(this.RuleProperty.expression, 10)
            )
        )
        function label(data, column, offset) {
            var result = $($.format('<label class="col-sm-{0} col-sm-offset-{1} control-label no-padding-right">', column, offset == undefined ? 0 : offset)).html(data.title)
                .attr('class', 'col-sm-2 control-label no-padding-right').attr('for', data.name)
            return result;
        }

        function input(data, column, offset) {
            var result = $($.format('<div class="col-sm-{0} col-sm-offset-{1}">', column, offset == undefined ? 0 : offset)).append(
                data.control = $('<input class="form-control" type="text">').attr('id', data.id).attr('name', data.name).attr('placeholder', data.title)
            )
            return result;
        }
    },
    //保存数据
    SaveData: function (rule) {
        var me = this;
        if (rule.RuleProperty == undefined) {
            rule.RuleProperty = {};
        }
        rule.RuleProperty.ruleName = me.RuleProperty.ruleName.control.val();
        rule.RuleProperty.expression = me.RuleProperty.expression.control.val();
    }
}
var PropertyConfig = {
    'start': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'end': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],

    'drafting': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'id': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        }],
    'approval': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'id': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        },
        {
            'id': 'ReturnProperty',
            'description': '回退设置',
            'js': 'ReturnProperty'
        }],

    'freedom': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    },
        {
            'UserProperty': 'UserProperty',
            'description': '人员设置',
            'js': 'UserProperty'
        },
        {
            'id': 'ReturnProperty',
            'description': '回退设置',
            'js': 'ReturnProperty'
        }],
    'condition': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'merging': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }],
    'branching': [{
        'id': 'BaseProperty',
        'description': '基本设置',
        'js': 'BaseProperty'
    }]
}
var Reflection = {
    'BaseProperty': BaseProperty,
    'UserProperty': UserProperty,
    'ReturnProperty': ReturnProperty
}
var Property = {
    InitailProperty: function (activity) {
        var root = $('#root');
        var container = $('.tabbable', root);
        container.empty();
        var ul = $('<ul class="nav nav-tabs" id="tabNav">');
        var content = $('<div class="tab-content">');
        var activityType = activity.GetActivityTypeName()
        var tmp = 0;
        $.each(PropertyConfig[activityType], function (i, val) {
            var id = Guid.NewGuid();
            var li = $('<li>');
            var property;
            if (tmp == 0) {
                li.attr('class', 'active').append($('<a aria-expanded="true" data-toggle="tab">').html(val.description).attr('href', '#' + id));
                property = $(' <div class="tab-pane in active">').attr('id', id);
                content.append(property);
            } else {
                li.attr('class', 'tab-red').append($('<a aria-expanded="false" data-toggle="tab">').html(val.description).attr('href', '#' + id));
                property = $(' <div class="tab-pane">').attr('id', id);
                content.append(property);
            }
            ul.append(li);
            Reflection[val.js]["InitialPage"](property, activity);
            property.unbind();
            ++tmp;
        });
        container.append(ul);
        container.append(content);

        $('.widget-caption', root).html(activity.ActivityName);
        return root;
    },
    SaveData: function (activity) {
        debugger;
        var activityType = activity.GetActivityTypeName()
        $.each(PropertyConfig[activityType], function (i, val) {
            Reflection[val.js].SaveData(activity);
        });
    }
}